package org.example.reactive.demo1.exception;

import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @author Gong.Yang
 */
@Order(-99)
@Component
public class GlobErrorHandler implements WebExceptionHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();

        if (ex instanceof BaseException baseException) {
            String message = baseException.getMessage();
            return response.writeWith(
                    Mono.just(response
                            .bufferFactory()
                            .wrap(message.getBytes(StandardCharsets.UTF_8))));
        }

        return response.writeWith(
                Mono.just(response
                        .bufferFactory()
                        .wrap("{\"json\":\"服务器忙\"}".getBytes(StandardCharsets.UTF_8))));
    }
}
